﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinImageTag
{
    public partial class FrmImage : Form
    {
        public FrmImage()
        {
            InitializeComponent();
        }

        private void FrmImage_Load(object sender, EventArgs e)
        {
            
        }

        private void lvImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            try { 
                if(picBox.Image!=null)
                    picBox.Image.Dispose();
                if (lvImages.SelectedItems.Count > 0)
                {
                    picBox.Image = new Bitmap(ConfigUtils.imgPath + lvImages.SelectedItems[0].Text);
                    //选中包含的标签
                    UncheckAll();
                    string[] imageTags = Path.GetFileNameWithoutExtension(lvImages.SelectedItems[0].Text).Split(' ');
                    foreach (string tag in imageTags)
                    {
                        for(int i = 0; i < chklstTags.Items.Count; i++)
                        {
                            if (tag.Equals(chklstTags.Items[i]))
                            {
                                chklstTags.SetItemChecked(i, true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void UncheckAll()
        {
            chklstTags.ClearSelected();
            for(int i = 0; i < chklstTags.Items.Count; i++)
            {
                chklstTags.SetItemChecked(i,false);
            }
        }

        private void btnSetTag_Click(object sender, EventArgs e)
        {
            try {
                if (lvImages.SelectedItems.Count == 0 || picBox.Image == null)
                {
                    MessageBox.Show("请选择好更改的图片!","图片未选",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                picBox.Image.Dispose();
                picBox.Image = null;
                string oldFileName = "";                
                oldFileName= lvImages.SelectedItems[0].Text;
                string ext= Path.GetExtension(lvImages.SelectedItems[0].Text);
                if (chklstTags.CheckedItems.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    //合并标签
                    foreach(string tag in chklstTags.CheckedItems)
                    {
                        sb.Append(tag);
                        sb.Append(" ");
                    }
                    //确定新名字
                    string newImageName=sb.ToString()+ ext;
                    //检查新名字是否存在
                    if (File.Exists(ConfigUtils.imgPath + newImageName))
                    {
                        MessageBox.Show("文件名重复!", "重名", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    //改名
                    //picBox.Load(ConfigUtils.imgPath + "abc.jpg");
                    File.Move(ConfigUtils.imgPath + oldFileName, ConfigUtils.imgPath + newImageName);
                    //更新列表
                    for(int i=0;i<lvImages.SelectedItems.Count;i++)
                    {
                        if (lvImages.SelectedItems[i].Text == oldFileName)
                        {
                            lvImages.SelectedItems[i].Text=newImageName;
                            picBox.Image = new Bitmap(ConfigUtils.imgPath + newImageName);
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddTag_Click(object sender, EventArgs e)
        {
            try { 
                FrmAddTag frm = new FrmAddTag();
                frm.ShowDialog();
                //增加新标签
                foreach(string tag in frm.tags)
                {
                    if(ExistsTag(tag)==false)
                    {
                        chklstTags.Items.Add(tag);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool ExistsTag(String tag)
        {
            bool result = false;
            foreach(String tagE in chklstTags.Items)
            {
                if (tag.Equals(tagE))
                {
                    result = true;
                    break;
                }
            }
            return result;
        }

        private void btnSaveTag_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (String tag in chklstTags.Items)
                {
                    sb.Append(tag);
                    sb.Append(" ");
                }
                //要保存的标签列表（逗号分隔）
                string tags = sb.ToString();
                FilesINI.WriteIni("config", "Tags", tags);
                MessageBox.Show("保存成功", "保存", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FrmImage_Shown(object sender, EventArgs e)
        {
            try
            {
                //读取目录下的所有文件
                string[] files = Directory.GetFiles(ConfigUtils.imgPath, "*");
                foreach (string file in files)
                {
                    //展示到列表
                    lvImages.Items.Add(file.Replace(ConfigUtils.imgPath, ""));
                }
                //读取标签
                string[] tags = ConfigUtils.tags.Split(' ');
                foreach (string tag in tags)
                {
                    chklstTags.Items.Add(tag);
                }
            }
            catch (DirectoryNotFoundException ex1)
            {
                MessageBox.Show("找不到指定的文件夹，请先到【系统】→【目录设置】中设置图片的文件夹位置", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("确定要删除所选的这些标签吗？", "删除确认", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
            {
                int i = 0;
                while (i < this.chklstTags.Items.Count)
                {
                    if (this.chklstTags.GetItemChecked(i))
                    {
                        this.chklstTags.Items.RemoveAt(i);
                        i = 0;
                    }
                    else
                    { i++; }
                }
            }
        }
    }
}
